package com.shuai.utils.hander.securityHander;

import com.alibaba.fastjson.JSON;
import com.shuai.enums.ErrorEnum;
import com.shuai.enums.SystemEnum;
import com.shuai.utils.returnVo.ReturnModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录失败的认证处理器
 *
 * @author shuai
 * @since 2022
 */
@Slf4j
@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException{
        //设置返回数据的字符集
        response.setContentType("application/json;charset=utf-8");
        //设置返回的数据
        response.getWriter().write(JSON.toJSONString(ReturnModel.failureInstance(SystemEnum.F400.getCode(),e.getMessage(),null)));
    }
}
